<?php 
function _json($s){
	header('Content-Type: application/json');
	echo $s;
}

function _jsonp($success=TRUE,$data=NULL){
	header('Content-Type: application/json');
	$result = array("success"=>$success);
	if($data){
		$result['data']=$data;
	}
	echo json_encode($result);
}

function highlight_word($text,$word){
	preg_match_all('~\w+~', $word, $m);
	if(!$m) return $text;
	$re = '~\\b(' . implode('|', $m[0]) . ')\\b~i';
	return preg_replace($re, '<span class="keyword">$0</span>', $text);
}

function compact_string($s){
	$s = trim($s);
	return preg_replace('!\s+!', ' ', $s);
}

function user_val($key){
	@session_start();
	if(isset($_SESSION['user'][$key])){
		return $_SESSION['user'][$key];
	}elseif (isset($_SESSION['user_config'][$key])) {
		return $_SESSION['user_config'][$key];
	}
	throw new Exception('Invalid Key:'.$key);
}

function inc($file){
	return $_SERVER['DOCUMENT_ROOT'].'/includes/'.$file;
}

function get_footer(){
	include_once(inc('footer.php'));
}
function e($s){
	echo($s);
}
function _($s){
	echo($s);
}
function now(){
	return date('Y-m-d H:i:s', time());
}

function deny_get_request(){
	if($_SERVER['REQUEST_METHOD']=='GET'){
		to_403();
		exit();
	}
}

function deny_anonymous(){
	@session_start();
	if(!isset($_SESSION['user'])){
		header("location:/login");
		exit();
	}
}
function time_ago($timestamp, $detailLevel = 1) {
	$periods = array("秒", "分钟", "小时", "天", "周", "个月", "年", "十年");
	$lengths = array("60", "60", "24", "7", "4.35", "12", "10");

	$now = time();

	// check validity of date
	if(empty($timestamp)) {
		return "Unknown time";
	}
	$difference=0;
	// is it future date or past date
	if($now > $timestamp) {
		$difference = $now - $timestamp;
		$tense = "前";
	}

	if ($difference == 0) {
		return "1秒前";
	}

	$remainders = array();

	for($j = 0; $j < count($lengths); $j++) {
		$remainders[$j] = floor(fmod($difference, $lengths[$j]));
		$difference = floor($difference / $lengths[$j]);
	}

	$difference = round($difference);

	$remainders[] = $difference;

	$string = "";

	for ($i = count($remainders) - 1; $i >= 0; $i--) {
		if ($remainders[$i]) {
			$string .= $remainders[$i] . "" . $periods[$i];
			$detailLevel--;

			if ($detailLevel <= 0) {
				break;
			}
		}
	}
	return $string . $tense;
}
function progress_bar($percentage){
	$class='ui-progress-bar blue';
	if($percentage==100){
		$class='ui-progress-bar success';
	}else if($percentage==80){
		$class='ui-progress-bar orange';
	}
	echo '<div class="'.$class.' ui-container" id="progress_bar">';
	echo '<div class="ui-progress" style="width: '.$percentage.'%;">';
	echo '</div>';
	echo '</div>';
}
function word_stylish_link($word,$familiarity=1){
	echo '<a href="/word/'.urlencode($word).'" class="word_link">'.word_stylish($word,$familiarity).'</a>';
}

function word_stylish($word,$familiarity=1){
	$class='unknown';
	if($familiarity==5){
		$class='remembered';
	}else if($familiarity==4){
		$class='familiar';
	}
	return '<span class="'.$class.' word">'.$word.'</span>';
}

function parameters_check($parameters){
	$result=true;
	if(is_array($parameters)){
		foreach ($parameters as $param) {
			if(!isset($param)){
				$result=false;
				break;
			}
		}
	}else{
		if(!isset($parameters))$result=false;
	}
	if(!$result){
		to_403();
		exit();
	}
	
}

function stylish_state($val1,$val2,$class){
	if($val1==$val2){
		echo 'class="'.$class.'"';
	}
	echo '';
}
function strip_quotes($s){
	$s = str_replace('"', "", $s);
	return str_replace("'", "", $s);
}

function to_404(){
	header("location:/404");
}

function to_403(){
	header("location:/403");
}

function search($array, $key, $value)
{
    $results = array();

    if (is_array($array))
    {
        if (isset($array[$key]) && $array[$key] == $value)
            $results[] = $array;

        foreach ($array as $subarray)
            $results = array_merge($results, search($subarray, $key, $value));
    }

    return $results;
}

function is_exsit($array,$key,$val){
	$arr = search($array,$key,$val);
	return count($arr)>0;
}

function is_file_exist($file_path){
	$path = $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.$file_path;
	return file_exists($path);
}

function is_avatar_exist($user_id){
	return is_file_exist(AVATAR_FOLDER.DIRECTORY_SEPARATOR.'avatar_'.$user_id.'.png');
}


function pagination($total){
	require_once(APP.'/includes/Pagination.class.php');
	$page = isset($_GET['page']) ? ((int) $_GET['page']) : 1;
	$pagination = (new Pagination());
	$pagination->setCurrent($page);
	$pagination->setTotal($total);
	$pagination->setRPP(RPP);
	$markup = $pagination->parse();
	echo $markup;
}

function lowercase($s){
	$s = str_replace('Ã','ã',$s);
	$s = str_replace('Á','á',$s);
	$s = str_replace('À','à',$s);
	$s = str_replace('Â','â',$s);
	$s = str_replace('Ç','ç',$s);
	$s = str_replace('É','é',$s);
	$s = str_replace('Ê','ê',$s);
	$s = str_replace('È','è',$s);
	$s = str_replace('Í','í',$s);
	$s = str_replace('Î','î',$s);
	$s = str_replace('Ì','ì',$s);
	$s = str_replace('Õ','õ',$s);
	$s = str_replace('Ó','ó',$s);
	$s = str_replace('Ô','ô',$s);
	$s = str_replace('Ò','ò',$s);
	$s = str_replace('Ú','ú',$s);
	$s = str_replace('Û','û',$s);
	$s = str_replace('Ù','ù',$s);
	$s = str_replace('Ü','ü',$s);
	return strtolower($s);
}


function avatar_url($user_id){
	echo AVATAR_FOLDER.'/'.'avatar_'.$user_id.'.png';
}

function user_url($user_id){
	echo '/person/'.intval($user_id);
}

function group_icon_url($group_id){
	echo '/uploads/groups/group_'.$group_id.'.png';
}

function topic_compose_url($group_id){
	echo '/group/'.$group_id.'/topic/compose';
}

function topic_edit_url($topic_id){
	echo '/group/topic/'.$topic_id.'/edit';
}

function group_topics_url($group_id=NULL){
	if($group_id){
		echo '/group/'.$group_id.'/topics';
	}else{
		echo '/group/topics';
	}
}
function topic_url($topic_id){
	echo '/group/topic/'.$topic_id;
}

function familiarity($i){
	switch (intval($i)) {
		case 1: return '模糊';
		case 2: return '认识';
		case 3: return '熟悉';
		case 4: return '拼写';
		case 5: return '运用';
	}
}
function familiarity_color($i){
	switch (intval($i)) {
		case 1: return '#80B3FF';
		case 2: return '#02779E';
		case 3: return '#FFCC25';
		case 4: return '#F18D05';
		case 5: return '#46B525';
	}
}
?>